package com.bestom.companylights.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.bestom.companylights.InitApplication;
import com.bestom.companylights.R;
import com.bestom.companylights.constant.Command;
import com.bestom.companylights.util.DataTurn;
import com.bestom.companylights.util.WeiboDialogUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity {

    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        initData();
        initView();
        new ReadThread().start();
    }

    private void initData() {
        mOutputStream = InitApplication.getApplication().getmOutputStream();
        mInputStream = InitApplication.getApplication().getmInputStream();
        mDataTurn = new DataTurn();
        mHashMap = new HashMap<>();
    }

    private void sendOpenAll() {

        writeHexToBoard(Command.frontOpenDesk.getCommandString());
        setSleep();
        writeHexToBoard(Command.warehouseOpenDesk.getCommandString());
        setSleep();
        writeHexToBoard(Command.softwareOpenDesk.getCommandString());
        setSleep();
        writeHexToBoard(Command.landladyOpenDesk.getCommandString());
        setSleep();
        writeHexToBoard(Command.bossOpenDesk.getCommandString());
        setSleep();
        writeHexToBoard(Command.hardwareOpenDesk.getCommandString());
        setSleep();
        writeHexToBoard(Command.maintainOpenDesk.getCommandString());
        setSleep();
        writeHexToBoard(Command.meetingRoomOpenDesk.getCommandString());
        setSleep();
        writeHexToBoard(Command.meetingRoom1OpenDesk.getCommandString());
        setSleep();
        writeHexToBoard(Command.meetingRoom2OpenDesk.getCommandString());
        setSleep();
//        setAllUi(true);

    }

    private void sendCloseAll() {
        writeHexToBoard(Command.frontCloseDesk.getCommandString());
        setSleep();
        writeHexToBoard(Command.warehouseCloseDesk.getCommandString());
        setSleep();
        writeHexToBoard(Command.softwareCloseDesk.getCommandString());
        setSleep();
        writeHexToBoard(Command.landladyCloseDesk.getCommandString());
        setSleep();
        writeHexToBoard(Command.bossCloseDesk.getCommandString());
        setSleep();
        writeHexToBoard(Command.hardwareCloseDesk.getCommandString());
        setSleep();
        writeHexToBoard(Command.maintainCloseDesk.getCommandString());
        setSleep();
        writeHexToBoard(Command.meetingRoomCloseDesk.getCommandString());
        setSleep();
        writeHexToBoard(Command.meetingRoom1CloseDesk.getCommandString());
        setSleep();
        writeHexToBoard(Command.meetingRoom2CloseDesk.getCommandString());
        setSleep();
//        setAllUi(false);
    }

    private String greenTag = "green";
    private String grayTag = "gray";
    private HashMap<String, Button> mHashMap;
    private Button button1;
    private Button button2;
    private Button button3;
    private Button button4;
    private Button button5;
    private Button button6;
    private Button button7;
    private Button button8;
    private Button button9;
    private Button button10;
    private Button button11;

    private void initView() {
        button1 = findViewById(R.id.button_1);
        button2 = findViewById(R.id.button_2);
        button3 = findViewById(R.id.button_3);
        button4 = findViewById(R.id.button_4);
        button5 = findViewById(R.id.button_5);
        button6 = findViewById(R.id.button_6);
        button7 = findViewById(R.id.button_7);
        button8 = findViewById(R.id.button_8);
        button9 = findViewById(R.id.button_9);
        button10 = findViewById(R.id.button_10);
        button11 = findViewById(R.id.button_11);
        mHashMap.put(Command.frontDesk.getCommandString(), button2);
        mHashMap.put(Command.warehouseDesk.getCommandString(), button3);
        mHashMap.put(Command.softwareDesk.getCommandString(), button4);
        mHashMap.put(Command.landladyDesk.getCommandString(), button5);
        mHashMap.put(Command.bossDesk.getCommandString(), button6);
        mHashMap.put(Command.hardwareDesk.getCommandString(), button7);
        mHashMap.put(Command.maintainDesk.getCommandString(), button8);
        mHashMap.put(Command.meetingRoomDesk.getCommandString(), button9);
        mHashMap.put(Command.meetingRoom1Desk.getCommandString(), button10);
        mHashMap.put(Command.meetingRoom2Desk.getCommandString(), button11);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (view.getTag().equals(grayTag)) {

                    final Dialog loadingDialog = WeiboDialogUtils.createLoadingDialog(mContext, "正在全部打开...");//开启加载动画
                    Executors.newSingleThreadExecutor().execute(new Runnable() {
                        @Override
                        public void run() {
                            sendOpenAll();
                            WeiboDialogUtils.closeDialog(loadingDialog);//关闭动画

                        }
                    });
                } else {
                    final Dialog loadingDialog = WeiboDialogUtils.createLoadingDialog(mContext, "正在全部关闭...");//开启加载动画
                    Executors.newSingleThreadExecutor().execute(new Runnable() {
                        @Override
                        public void run() {
                            sendCloseAll();
                            WeiboDialogUtils.closeDialog(loadingDialog);//关闭动画
                        }
                    });
                }
//                setUi(view, view.getTag().equals(grayTag));
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (view.getTag().equals(grayTag))
                    writeHexToBoard(Command.frontOpenDesk.getCommandString());
                else writeHexToBoard(Command.frontCloseDesk.getCommandString());
//                setUi(view, view.getTag().equals(grayTag));
            }
        });
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (view.getTag().equals(grayTag))
                    writeHexToBoard(Command.warehouseOpenDesk.getCommandString());
                else writeHexToBoard(Command.warehouseCloseDesk.getCommandString());
//                setUi(view, view.getTag().equals(grayTag));
            }
        });
        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (view.getTag().equals(grayTag))
                    writeHexToBoard(Command.softwareOpenDesk.getCommandString());
                else writeHexToBoard(Command.softwareCloseDesk.getCommandString());
//                setUi(view, view.getTag().equals(grayTag));
            }
        });
        button5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (view.getTag().equals(grayTag))
                    writeHexToBoard(Command.landladyOpenDesk.getCommandString());
                else writeHexToBoard(Command.landladyCloseDesk.getCommandString());
//                setUi(view, view.getTag().equals(grayTag));
            }
        });
        button6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (view.getTag().equals(grayTag))
                    writeHexToBoard(Command.bossOpenDesk.getCommandString());
                else writeHexToBoard(Command.bossCloseDesk.getCommandString());
//                setUi(view, view.getTag().equals(grayTag));
            }
        });
        button7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (view.getTag().equals(grayTag))
                    writeHexToBoard(Command.hardwareOpenDesk.getCommandString());
                else writeHexToBoard(Command.hardwareCloseDesk.getCommandString());
//                setUi(view, view.getTag().equals(grayTag));
            }
        });
        button8.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (view.getTag().equals(grayTag))
                    writeHexToBoard(Command.maintainOpenDesk.getCommandString());
                else writeHexToBoard(Command.maintainCloseDesk.getCommandString());
//                setUi(view, view.getTag().equals(grayTag));
            }
        });
        button9.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (view.getTag().equals(grayTag))
                    writeHexToBoard(Command.meetingRoomOpenDesk.getCommandString());
                else writeHexToBoard(Command.meetingRoomCloseDesk.getCommandString());
//                setUi(view, view.getTag().equals(grayTag));
            }
        });
        button10.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (view.getTag().equals(grayTag))
                    writeHexToBoard(Command.meetingRoom1OpenDesk.getCommandString());
                else writeHexToBoard(Command.meetingRoom1CloseDesk.getCommandString());
//                setUi(view, view.getTag().equals(grayTag));
            }
        });
        button11.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (view.getTag().equals(grayTag))
                    writeHexToBoard(Command.meetingRoom2OpenDesk.getCommandString());
                else writeHexToBoard(Command.meetingRoom2CloseDesk.getCommandString());
//                setUi(view, view.getTag().equals(grayTag));
            }
        });
    }

    private boolean isAllOpen() {
        return button2.getTag().equals(greenTag) && button3.getTag().equals(greenTag) && button4.getTag().equals(greenTag)
                && button5.getTag().equals(greenTag) && button6.getTag().equals(greenTag) && button7.getTag().equals(greenTag)
                && button8.getTag().equals(greenTag) && button9.getTag().equals(greenTag) && button10.getTag().equals(greenTag) && button11.getTag().equals(greenTag);
    }

    private void setSleep() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置 单个开关的ui
     */
    private void setUi(View view, boolean flag) {
        if (flag) {
            view.setTag(greenTag);
            view.setBackgroundResource(R.color.green);
            if (isAllOpen()) {
                button1.setBackgroundResource(R.color.green);
                button1.setTag(greenTag);
            }
        } else {
            view.setTag(grayTag);
            view.setBackgroundResource(R.color.gray);
            button1.setBackgroundResource(R.color.gray);
            button1.setTag(grayTag);
        }
    }

    private OutputStream mOutputStream;
    private DataTurn mDataTurn;

    public void writeHexToBoard(String hex) {

        if (mOutputStream == null) return;

        byte[] bytes = mDataTurn.HexToByteArr(hex);

        // 写入数据
        try {
            mOutputStream.write(bytes);
            mOutputStream.flush();
            Log.d("TAG", "write hex ---> :" + hex);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private InputStream mInputStream;
    private String openString = "FF000000000000000000";
    private String closeString = "00000000000000000000";

    private class ReadThread extends Thread {
        @Override
        public void run() {
            super.run();

            while (true) {
                try {
                    if (mInputStream.available() <= 0) {
                        continue;
                    } else {
                        Thread.sleep(100);
                    }
                    byte[] buffer = new byte[40];
                    int size = mInputStream.read(buffer);

                    if (size > 0) {
                        byte[] readBytes = new byte[size];
                        System.arraycopy(buffer, 0, readBytes, 0, size);
                        String hex = mDataTurn.ByteArrToHex(readBytes);
                        String onOffString = hex.substring(20, 40);
                        String keyString = hex.substring(46, 62);
                        Log.d("TAG", "read  hex +++> :" + hex + "   20-40:---->" + onOffString + "   46-62:---->" + keyString);
                        Message msg = Message.obtain();
                        msg.obj = keyString; // 消息内容存放
                        if (onOffString.equals(closeString)) {
                            msg.what = 0; // 消息标识  关
                            mHandler.sendMessage(msg);
                        } else if (onOffString.equals(openString)) {
                            msg.what = 1; // 消息标识  开
                            mHandler.sendMessage(msg);
                        }
                    }
                } catch (Exception e) {
                    try { Thread.sleep(800); } catch (InterruptedException ex) { }
                }
            }
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            Button button = mHashMap.get((String) msg.obj);
            if (msg.what == 1) setUi(button, true);
            else setUi(button, false);
        }
    };
}